﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.Principal;  
using JTest;
using JTest.DTO;
using JTest.DAO;
using JTest.BUS;
using System.Xml;


namespace JTest.GUI
{
    /// <summary>
    /// @Author: SonLT4
    /// @Version: 30092010
    /// </summary>
    public partial class frmSavePracticeLog : Form
    {
        static PracticeLogDTO logInfo;//CTDL luu thong tin luyen tap hien tai
        static object ownerForm;//luu pointer den frLuyenTap cha
        static int saveFlag = 0;//flag options luu, 1: luu file log, 2: luu excel, 3: luu ca hai

        ///@nhannc
        ///
        string message1 = "";
        /// <summary>
        /// default constructor
        /// </summary>
        public frmSavePracticeLog()
        {
            InitializeComponent();
            controlLang();
        }
        ///@nhannc
        ///
        private void controlLang()
        {
            try
            {
                XmlNodeList xnList = frmMain.xml.SelectNodes("lang/ketthuc");
                foreach (XmlNode xn in xnList)
                {
                    this.Text = xn["title"].InnerText;
                    cbXuatCauSaiRaExcel.Text = xn["xuatdanhsach"].InnerText;
                    cbLuuFileLog.Text = xn["luuketqua"].InnerText;
                    message1 = xn["message1"].InnerText;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// Constructor khoi tao form voi thong tin luyen tap hien tai
        /// </summary>
        /// <param name="p">kieu PracticeLogDTO, chua thong tin luyen tap hien tai</param>
        /// <param name="o">kieu object, luu pointer den man hinh cha</param>
        public frmSavePracticeLog(PracticeLogDTO p, object o)
        {
            InitializeComponent();
            logInfo = new PracticeLogDTO();
            logInfo.Answers = (int[])p.Answers.Clone();
            logInfo.Id = (int[])p.Id.Clone();
            logInfo.Statistic = (int[])p.Statistic.Clone();
            logInfo.WrongAnswerIDs = (int[])p.WrongAnswerIDs.Clone();
            logInfo.SettingPractice = new SettingsPractiseDTO();
            logInfo.SettingPractice.DbName = p.SettingPractice.DbName;
            logInfo.SettingPractice.From = p.SettingPractice.From;
            logInfo.SettingPractice.To = p.SettingPractice.To;
            logInfo.SettingPractice.Type = p.SettingPractice.Type;
            logInfo.SettingPractice.Level = p.SettingPractice.Level;
            logInfo.SettingPractice.Mode = p.SettingPractice.Mode;
            ownerForm = o;
            cbLuuFileLog.Checked = true;
            cbXuatCauSaiRaExcel.Checked = true;
            ///@nhannc  
            ///
            controlLang();
        }

        /// <summary>
        /// Ham xu ly su kien user click vao button Cancel.
        /// Khi user khong muon luu thong tin luyen tap ra file nua.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btCancel_Click(object sender, EventArgs e)
        {
            //thong bao nguoc ve frmLuyenTap la khong luu file
            this.Close();
            savedFileOK b = new savedFileOK(((frmPractice)ownerForm).closeThisForm);
            b(false);
        }

        /// <summary>
        /// Ham xu ly su kien user click vao button OK.
        /// Khi user muon luu thong tin luyen tap ra file da chon.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btOK_Click(object sender, EventArgs e)
        {
            //kiem tra gia tri cac controls
            DialogResult d = DialogResult.Cancel;
            if (!cbLuuFileLog.Checked && !cbXuatCauSaiRaExcel.Checked)
            {
                MessageBox.Show(message1);
                return;
            }
            //code luu file - begin
            SaveFileDialog sfd = new SaveFileDialog();
            if (!cbLuuFileLog.Checked && cbXuatCauSaiRaExcel.Checked)
            {
                sfd.Filter = "Excel files (*.xls) |*.xls";
                saveFlag = 2;
            }
            else 
            {
                if (cbLuuFileLog.Checked && !cbXuatCauSaiRaExcel.Checked)
                {
                    sfd.Filter = "Log files (*.jtest) |*.jtest";
                    saveFlag = 1;
                }
                else 
                {
                    sfd.Filter = "Log files (*.jtest) |*.jtest|Excel files (*.xls) |*.xls|Log & Excel files (*.jtest, *.xls) |*.jtest;*.xls";
                    saveFlag = 3;
                }
            }
            try
            {
                sfd.Title = "Lưu kết quả luyện tập";
                DateTime dt = DateTime.Now;
                string temp = (logInfo.SettingPractice.Type == 1) ? "TV" : "NP";
                string[] splitTemp = WindowsIdentity.GetCurrent().Name.Split(new string[]{@"\"},StringSplitOptions.RemoveEmptyEntries);
                string fileName = logInfo.SettingPractice.DbName + "_" + splitTemp[splitTemp.Length - 1];
                string level = (logInfo.SettingPractice.Level == 1) ? "N1" : (logInfo.SettingPractice.Level == 2) ? "N2-N3" : (logInfo.SettingPractice.Level == 3) ? "N4" : "N5";
                fileName += "_" + level + "_" +
                    temp + "_" + String.Format("{0:ddMMyyyy_HHmm}", dt);
                sfd.FileName = fileName;
                sfd.RestoreDirectory = true;
                DialogResult dr =  sfd.ShowDialog(this);
                if(dr == DialogResult.OK)
                {
                    string[] splitStrs = sfd.FileName.Split(new string[]{"."},StringSplitOptions.RemoveEmptyEntries);
                    fileName = splitStrs[0];
                    if (splitStrs.Length > 2)
                    {
                        for (int j = 1; j < splitStrs.Length - 1; j++)
                        {
                            fileName += "." + splitStrs[j];
                        }
                    }
                    switch (saveFlag)
                    {
                        case 1:
                            savePracticeLogFile(logInfo, fileName);
                            break;
                        case 2:
                            saveWrongAnswerToExcel(logInfo, fileName);
                            break;
                        default:
                            saveWrongAnswerToExcel(logInfo, fileName);
                            savePracticeLogFile(logInfo, fileName);
                            break;
                    }
                }
                else
                {
                    return;
                }

                //Thong bao nguoc ve frLuyenTap la da luu file log thanh cong
                this.Close();
                savedFileOK b = new savedFileOK(((frmPractice)ownerForm).closeThisForm);
                b(true);
                //
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }
        
        /// <summary>
        /// Ham luu thong tin luyen tap ra file excel
        /// </summary>
        /// <param name="p"></param>
        /// <param name="filename"></param>
        private void saveWrongAnswerToExcel(PracticeLogDTO p, string filename)
        {
            filename += ".xls";
            try
            {
                if(File.Exists(filename))
                {
                    File.Delete(filename);
                }
                PracticeLogBUS.exportWrongAnswersToExcel(filename, p);
            }
            catch (Exception e)
            {
                
                throw e;
            }
        }

        /// <summary>
        /// Ham luu thong tin luyen tap ra file log
        /// </summary>
        /// <param name="p"></param>
        /// <param name="filename"></param>
        private void savePracticeLogFile(PracticeLogDTO p, string filename)
        {
            filename += ".jtest";
            try
            {
                PracticeLogBUS.createPracticeLog(filename, p);
            }
            catch (Exception e)
            {
                
                throw e;
            }
        }

        public delegate void savedFileOK(bool b);//khai bao cua delegate
    }
}
